package handlers

import (
	"archive/zip"
	awesomehttp "gitee.com/jjawesomejj/awesomehttp/system"
	"gitee.com/jjawesomejj/awesomehttp/system/httpContext"
	"io"
	"os"
	"path/filepath"
)

type DownloadHandler struct {
	awesomehttp.HttpBaseHandler
}

func (context *DownloadHandler) GetModuleName() string {
	return "/api/download/"
}

type HttpWrite struct {
	Context *httpContext.HttpContext
}

func (write *HttpWrite) Write(bytes []byte) (int, error) {
	i, err := write.Context.Response.Write(bytes)
	if err != nil {
		return 0, err
	}
	return i, nil
}
func (context *DownloadHandler) ActionTest() interface{} {
	dirPath := "D:\\Win软件市场"

	// 创建 ZIP 写入器buff
	zipBuffer := &HttpWrite{
		Context: context.HttpContext,
	}
	zipWriter := zip.NewWriter(zipBuffer)
	defer zipWriter.Close()
	//遍历文件夹
	err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
		// 忽略文件夹本身
		if path == dirPath {
			return nil
		}
		// 创建文件头
		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}
		header.Name = filepath.ToSlash(path[len(dirPath)+1:])
		// 写入文件头
		writer, err := zipWriter.CreateHeader(header)
		if err != nil {
			return err
		}
		// 如果是文件，写入文件内容
		if !info.IsDir() {
			file, err := os.Open(path)
			if err != nil {
				return err
			}
			defer file.Close()
			_, err = io.Copy(writer, file)
			if err != nil {
				return err
			}
			//err = ioRead(file, func(buff []byte) error {
			//	_, err2 := writer.Write(buff)
			//	if err2 != nil {
			//		return err2
			//	}
			//	return nil
			//})
			if err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return err
	}
	return ""
}

func ioRead(file *os.File, fun func(buff []byte) error) error {
	isRun := true
	index := int64(0)
	for isRun {
		buff := make([]byte, 2024)
		read, err := file.ReadAt(buff, index)
		if err != nil && io.EOF != err {
			panic(err)
		}
		index = index + int64(read)
		if read != 0 {
			err := fun(buff[0:read])
			if err != nil {
				return err
			}
		} else {
			isRun = false
		}
	}
	return nil
}
